package com.qcit.api

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.qcit.annotation.ACTIVITY
import com.qcit.annotation.CALL
import com.qcit.annotation.FRAGMENT
import com.qcit.annotation.bean.ARouterBean
import com.qcit.api.cache.RouteCacheData
import java.lang.Exception

class ARouterManager private constructor() {
    private var group = ""
    private var path = ""
    private val FILE_GROUP_NAME = "ARouter$\$Group$$"
    private val APT_PACKAGE_DEFULT = "com.qcit.apt"//APT存放的包名
    private var pathMap = HashMap<String,Class<out IARouterPath>>()
    private var pathBeanMap = HashMap<String, ARouterBean>()
    companion object {
        val instance: ARouterManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ARouterManager() }
    }
    fun build(path:String):BundleManager{
//        if (PathRule.checkRule(path)){
//
//        }
//        return null
        // 截取组名  /order/Order_MainActivity  finalGroup=order
        val finalGroup = path.substring(1, path.indexOf("/", 1))
        // 证明没有问题，没有抛出异常
        this.path = path // 最终的效果：如 /order/Order_MainActivity
        this.group = finalGroup // 例如：order，personal
        return BundleManager()
    }
    fun navigation(context:  Fragment, bundleManager: BundleManager, code:Int?):Any?{
        var groupClassName = context.activity!!.packageName+"."+FILE_GROUP_NAME+group
        var loadGroup = RouteCacheData.routerGroupCache[group]
        if (null == loadGroup){
            // 缓存里面没有东东
            // 加载APT路由组Group类文件 例如：ARouter$$Group$$order
            val aClass = Class.forName(groupClassName)
            // 初始化类文件
            loadGroup = aClass.newInstance() as IARouterGroup
            RouteCacheData.routerGroupCache.put(group,loadGroup)
        }
        pathMap.clear()
        if (loadGroup.getGroupCache(pathMap).isEmpty()){
            Toast.makeText(context.context, "路由表错误", Toast.LENGTH_SHORT).show()
            return null
        }
        var loadPath = RouteCacheData.routerPathCache.get(path)
        if (null == loadPath){
            var clazz = loadGroup.getGroupCache(pathMap).get(group)
            loadPath = clazz!!.newInstance()
            RouteCacheData.routerPathCache.put(path,loadPath)
        }
        if (null != loadPath){
            if (!pathBeanMap.isEmpty())
                pathBeanMap.clear()
            if (loadPath.getPathCache(pathBeanMap).isEmpty()){
                Toast.makeText(context.context, "路由表错误", Toast.LENGTH_SHORT).show()
                return null
            }
            var routerBean = pathBeanMap[path]
            if (routerBean != null) {
                when (routerBean.type) {
                    ACTIVITY -> {
                        val intent: Intent = Intent(
                            context.context,
                            routerBean.clazz
                        ) // 例如：getClazz == Order_MainActivity.class
                        intent.putExtras(bundleManager.bundle) // 携带参数
                        // context.startActivity(intent, bundleManager.getBundle()); // 大部分手机有问题，没有任何反应
                        if (null != code)
                            context.startActivityForResult(intent,code)
                        else
                            context.startActivity(intent)
                    }
                    FRAGMENT ->{
                        var claz = routerBean.clazz?.newInstance() as Fragment
                        return claz
                    }
                    CALL ->{
                        var claz = routerBean.clazz?.newInstance() as Call
                        bundleManager.call = claz
                        return bundleManager.call
                    }
                }
            }

        }
        return null
    }
    @RequiresApi(Build.VERSION_CODES.S)
    fun navigation(context:  Activity, bundleManager: BundleManager, code:Int?):Any?{
        var groupClassName = APT_PACKAGE_DEFULT+"."+FILE_GROUP_NAME+group
        var loadGroup = RouteCacheData.routerGroupCache[group]
        if (null == loadGroup){
            // 缓存里面没有东东
            // 加载APT路由组Group类文件 例如：ARouter$$Group$$order
           try {
               val aClass = Class.forName(groupClassName)
               loadGroup = aClass.newInstance() as IARouterGroup
               RouteCacheData.routerGroupCache.put(group,loadGroup)
           }catch (e:Exception){
               Toast.makeText(context, "请检查访问路由"+path+"是否正确", Toast.LENGTH_SHORT).show()
              return null
           }
            // 初始化类文件

        }
        pathMap.clear()
        if (loadGroup.getGroupCache(pathMap).isEmpty()){
            Toast.makeText(context, "路由表错误", Toast.LENGTH_SHORT).show()
            return null
        }
        var loadPath = RouteCacheData.routerPathCache.get(path)
        if (null == loadPath){
            var clazz = loadGroup.getGroupCache(pathMap).get(group)
            loadPath = clazz!!.newInstance()
            RouteCacheData.routerPathCache.put(path,loadPath)
        }
        if (null != loadPath){
            if (!pathBeanMap.isEmpty())
                pathBeanMap.clear()
            if (loadPath.getPathCache(pathBeanMap).isEmpty()){
                Toast.makeText(context, "路由表错误", Toast.LENGTH_SHORT).show()
                return null
            }
            var routerBean = pathBeanMap[path]
            if (routerBean != null) {
                when (routerBean.type) {
                    ACTIVITY -> {
                        val intent = Intent(
                            context,
                            routerBean.clazz
                        ) // 例如：getClazz == Order_MainActivity.class
                        intent.putExtras(bundleManager.bundle) // 携带参数
                        // context.startActivity(intent, bundleManager.getBundle()); // 大部分手机有问题，没有任何反应
                        if (null != code)
                            context.startActivityForResult(intent,code)
                        else
                            context.startActivity(intent)
                    }
                    FRAGMENT ->{
                        var claz = routerBean.clazz?.newInstance() as Fragment
                        return claz
                    }
                    CALL ->{
                        var claz = routerBean.clazz?.newInstance() as Call
                        bundleManager.call = claz
                        return bundleManager.call
                    }
                }
            }
        }

        return null
    }
}